package me.bincker.formwork.web.core.service.impl

import me.bincker.formwork.web.core.exception.NotFoundException
import me.bincker.formwork.web.core.repository.IBaseRepository
import me.bincker.formwork.web.core.service.IBaseService
import org.springframework.data.domain.Example
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import javax.persistence.EntityNotFoundException

open class BaseServiceImpl<T>(private val repository: IBaseRepository<T>): IBaseService<T> {
    override fun findAll(pageable: Pageable) = repository.findAll(pageable)

    override fun findAll() = repository.findAll()

    override fun findAll(sort: Sort) = repository.findAll(sort)

    override fun findAllById(ids: Iterable<String>) = repository.findAllById(ids)

    override fun <S : T> saveAll(entities: Iterable<S>) = repository.saveAll(entities)

    override fun deleteInBatch(entities: Iterable<T>) = repository.deleteInBatch(entities)

    override fun deleteAllInBatch() = repository.deleteAllInBatch()

    override fun getOne(id: String?): T {
        try{
            return repository.getOne(id ?: throw NotFoundException())
        }catch (e: EntityNotFoundException){
            throw NotFoundException(e)
        }
    }

    override fun <S : T> findAll(example: Example<S>) = repository.findAll(example)

    override fun <S : T> findAll(example: Example<S>, sort: Sort) = repository.findAll(example, sort)

    override fun <S : T> save(entity: S) = repository.save(entity)

    override fun findById(id: String?) = repository.findById(id ?: throw NotFoundException()).orElse(null)

    override fun existsById(id: String) = repository.existsById(id)

    override fun count() = repository.count()

    override fun deleteById(id: String) = repository.deleteById(id)

    override fun delete(entity: T) = repository.delete(entity)

    override fun deleteAll(entities: Iterable<T>) = repository.deleteAll(entities)

    override fun deleteAll() = repository.deleteAll()

    override fun <S : T> findOne(example: Example<S>) = repository.findOne(example).orElse(null)

    override fun <S : T> findAll(example: Example<S>, pageable: Pageable) = repository.findAll(example, pageable)

    override fun <S : T> count(example: Example<S>) = repository.count(example)

    override fun <S : T> exists(example: Example<S>) = repository.exists(example)
}
